﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Web.Controllers
{
    public class ProductController : CommonController
    {
        public ProductController() { }

        public ActionResult Index(string search)
        {
            var data = EdexContext.GetItems(search);
            return View(data);
        }

        public ActionResult Details(Guid id)
        {
            var data = EdexContext.GetItemDetails(id);
            return View(data);
        }

        public ActionResult DetailsNew()
        {
            return View();
        }

        public ActionResult MapDetailsEdit(Guid id)
        {
            var data = EdexContext.GetItemMapDetails(id.ToString());
            return View(data);
        }

        public ActionResult MapDetailsSave(Guid ITEM_GUID, Guid SUPPLIER_ITEM_GUID)
        {
            EdexContext.SaveItemMap(ITEM_GUID, SUPPLIER_ITEM_GUID);
            return Content("OK");
        }

        public ActionResult MapDetailsByInvoiceLineEdit(Guid id)
        {
            var line = EdexContext.GetOutgoingInvoiceLine(id.ToString());
            var data = EdexContext.GetItemMapDetails(line.ITEM_GUID.ToString());

            return View("MapDetailsEdit", data);
        }

        public ActionResult FindAndReturnHtmlList(string id)
        {
            var data = EdexContext.GetItems(id);
            var result_string = String.Join(String.Empty, data.Select(r => String.Format("<option value='{0}'>{1}</option>", r.GUID_RECORD, r.ITEM_NAME)));

            return Content(result_string);
        }

        public ActionResult FindAndReturnJson(string term)
        {
            var data = EdexContext
                .GetItems(term)
                .Select(r => new
                {
                    id = r.GUID_RECORD,
                    label = r.ITEM_NAME,
                    value = (String.IsNullOrEmpty(r.ARTICLE) ? String.Empty : r.ARTICLE + " ") + r.ITEM_NAME + " (" + r.EXT_KEY + ")"
                });

            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Save(EdexApiClient.WH_ITEMS record)
        {
            if (record.GUID_RECORD == null || record.GUID_RECORD == Guid.Empty)
                EdexContext.AddItem(record);
            else
                EdexContext.UpdateItem(record);

            return Content("OK");
        }

        public ActionResult Delete(string id)
        {
            EdexContext.DeleteItem(id);
            return Content("OK");
        }

    }
}
